package org.jvm.classpath.entry;


import org.jvm.util.JvmUtil;

import java.io.*;
import java.nio.charset.Charset;
import java.util.zip.ZipInputStream;

public class ZipEntry implements Entry {

    /**
     * 类目录
     */
    private String absDir;

    public ZipEntry(String path) {
        this.absDir = path.endsWith(File.separator) ? path : path.concat(File.separator);
    }

    public String getAbsDir() {
        return absDir;
    }

    public void setAbsDir(String absDir) {
        this.absDir = absDir;
    }

    public byte[] readClass(String className) {
        FileInputStream input = null;
        ZipInputStream zipInputStream = null;
        try {
            //获取文件输入流
            input = new FileInputStream(absDir);
            //获取ZIP输入流(一定要指定字符集Charset.forName("GBK")否则会报java.lang.IllegalArgumentException: MALFORMED)
            zipInputStream = new ZipInputStream(new BufferedInputStream(input), Charset.forName("GBK"));
            java.util.zip.ZipEntry ze;
            for (ze = zipInputStream.getNextEntry(); ze != null; ze = zipInputStream.getNextEntry()) {
                if (!ze.isDirectory() && ze.getName().endsWith(className)) {
                    return JvmUtil.readInputStream(zipInputStream);
                }
            }
        } catch (Exception e) {
            return null;
        } finally {
            try {
                input.close();
                zipInputStream.closeEntry();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public String getPath() {
        return getAbsDir();
    }
}
